package com.lancoo.znbkxx.teacher.ui.fragment

import android.graphics.Color
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.view.MotionEvent
import android.view.View
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.gif.GifDrawable
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.AudioListAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.databinding.FmtRecordingBinding
import com.lancoo.znbkxx.teacher.utils.AudioRecord
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.viewmodel.HardSolutionViewModel
import com.lancoo.znbkxx.teacher.widget.PopupList
import com.luck.picture.lib.entity.LocalMedia

import java.lang.Exception
import kotlin.math.abs

/**
 * @author : wealive
 * @date   : 2020/4/9 10:18
 * @desc   :
 */
class RecordingFragment : BaseVMFragment<HardSolutionViewModel, FmtRecordingBinding>(),
        View.OnClickListener, BaseQuickAdapter.OnItemClickListener,
        BaseQuickAdapter.OnItemLongClickListener, MediaPlayer.OnPreparedListener,
        MediaPlayer.OnCompletionListener, PopupList.PopupListListener {
    private val audioRecord by lazy { AudioRecord(requireContext()) }
    private lateinit var audioListAdapter: AudioListAdapter
    private val list = mutableListOf<LocalMedia>()
    private var startTime: Long = 0
    private var endTime: Long = 0
    private var mediaPlayer: MediaPlayer? = null
    private var gifView: ImageView? = null
    private var previousGifView: ImageView? = null
    private var currentPosition: Int = -1
    private var previousPosition: Int = -1
    private val popupList by lazy { PopupList(requireContext()) }

    //    private var remaindStyle = false
//    private var currentOperateIndex = -1
    private val strList = listOf("删除")

    companion object {
        fun newInstance(audioList: ArrayList<LocalMedia>): RecordingFragment {
            val fragment = RecordingFragment()
            val bundle = Bundle()
            bundle.putParcelableArrayList("audio", audioList)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun providerContext(): Any? {
        return activity
    }

    override fun providerVMClass(): Class<HardSolutionViewModel>? {
        return HardSolutionViewModel::class.java
    }

    override fun setLayoutID(): Int {
        return R.layout.fmt_recording
    }

    override fun initView() {
        binding.ivRecording.setOnClickListener(this)
        binding.btnConfirm.setOnClickListener(this)
        initRecyclerView()
    }

    private fun initRecyclerView() {
        val audioList = requireArguments().getParcelableArrayList<LocalMedia>("audio")
        list.addAll(audioList!!)
        audioListAdapter = AudioListAdapter(R.layout.item_recording, list)
        audioListAdapter.onItemClickListener = this
        audioListAdapter.onItemLongClickListener = this
        binding.rv.layoutManager = LinearLayoutManager(requireContext())
        binding.rv.adapter = audioListAdapter
    }

//    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
//        when (event?.action) {
//            MotionEvent.ACTION_DOWN -> {
//                binding.cpb.visibility = View.VISIBLE
//                binding.cpb.setPercentData(
//                        100f,
//                        "%",
//                        LinearInterpolator(),
//                        1
//                )
//                audioRecord.startRecord()
//                startTime = System.currentTimeMillis()
//            }
//            MotionEvent.ACTION_UP -> {
//                binding.cpb.end()
//                binding.cpb.visibility = View.GONE
//                endTime = System.currentTimeMillis()
//                if (abs(endTime - startTime) < 1000) {
//                    Handler().postDelayed(
//                            { audioRecord.stopRecord() },
//                            1000
//                    )
//                    return true
//                }
//                audioRecord.stopRecord()
//                val localMedia = LocalMedia()
//                localMedia.path = audioRecord.getPath()
//                localMedia.androidQToPath = audioRecord.getPath()
//                localMedia.mimeType = "audio/" + audioRecord.getPath()
//                        .substring(audioRecord.getPath().lastIndexOf(".") + 1)
//                localMedia.duration = endTime - startTime
//                audioListAdapter.addData(localMedia)
//                (parentFragment as CommentDetailFragment).saveRecord(1, localMedia)
//            }
//        }
//        binding.ivRecording.performClick()
//        return false
//    }

    private fun startRecord() {
        binding.cpb.visibility = View.VISIBLE
        binding.cpb.setPercentData(
                100f,
                "%",
                LinearInterpolator(),
                1
        )
        audioRecord.startRecord()
        startTime = System.currentTimeMillis()
    }

    private fun endRecord() {
        binding.cpb.end()
        binding.cpb.visibility = View.GONE
        endTime = System.currentTimeMillis()
        if (abs(endTime - startTime) < 1000) {
            Handler().postDelayed(
                    { audioRecord.stopRecord() },
                    1000
            )
            MyToast.showToast("说话时间太短")
            return
        }
        audioRecord.stopRecord()
        val localMedia = LocalMedia()
        localMedia.path = audioRecord.getPath()
        localMedia.androidQToPath = audioRecord.getPath()
        localMedia.mimeType = "audio/" + audioRecord.getPath()
                .substring(audioRecord.getPath().lastIndexOf(".") + 1)
        localMedia.duration = endTime - startTime
        audioListAdapter.addData(localMedia)
        (parentFragment as CommentDetailFragment).saveRecord(1, localMedia)
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_confirm -> (parentFragment as CommentDetailFragment).switchToPublish(list.size)
            R.id.iv_recording -> {
                if (binding.ivRecording.tag == "start") {
                    startRecord()
                    binding.ivRecording.tag = "end"
                } else {
                    endRecord()
                    binding.ivRecording.tag = "start"
                }
            }
        }
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        if (adapter is AudioListAdapter) {
            previousPosition = currentPosition
            currentPosition = position
            gifView =
                    adapter.getViewByPosition(binding.rv, currentPosition,
                            R.id.iv_speaker) as ImageView
            if (previousPosition != -1) {
                previousGifView = adapter.getViewByPosition(
                        binding.rv,
                        previousPosition,
                        R.id.iv_speaker
                ) as ImageView
            }
            playAudio(list[position].path)
            Glide.with(requireContext()).asGif().load(R.drawable.icon_speaker)
                    .into(gifView!!)
        }
    }

    override fun onItemLongClick(adapter: BaseQuickAdapter<*, *>?, view: View?,
            position: Int): Boolean {
        val location = IntArray(2)
        val imageView = view?.findViewById<ImageView>(R.id.iv_player)!!
        imageView.getLocationInWindow(location)
        val x = location[0] + imageView.width / 2
        val y = location[1]
        popupList.showPopupListWindow(view.findViewById<ImageView>(R.id.iv_player), position,
                x.toFloat(), y.toFloat(), strList, this)
        return true
    }

    private fun playAudio(path: String) {
        try {
            if (mediaPlayer != null && mediaPlayer!!.isPlaying) {
                mediaPlayer?.stop()
                mediaPlayer?.reset()
            } else {
                mediaPlayer = MediaPlayer()
            }
            if (path.contains("storage")) {
                mediaPlayer?.setDataSource(path)
            } else {
                mediaPlayer?.setDataSource(requireContext(), Uri.parse(path))
            }
            mediaPlayer?.prepareAsync()
            mediaPlayer?.setOnPreparedListener(this)
            mediaPlayer?.setOnCompletionListener(this)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onPrepared(mp: MediaPlayer?) {
        mp?.start()
        val drawable = gifView!!.drawable as? GifDrawable
        drawable?.start()
        if (previousGifView != null) {
            val drawablePrevious = previousGifView!!.drawable as? GifDrawable
            drawablePrevious?.stop()
            previousGifView!!.setImageResource(R.mipmap.icon_speaker)
        }
    }

    override fun onCompletion(mp: MediaPlayer?) {
        val drawable = gifView!!.drawable as? GifDrawable
        if (drawable != null && drawable.isRunning) {
            drawable.stop()
            gifView!!.setImageResource(R.mipmap.icon_speaker)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer?.release()
        mediaPlayer = null
    }

    override fun onResume() {
        super.onResume()
        mediaPlayer?.pause()
    }

    override fun dismissPopupList() {

    }

    override fun onPopupListClick(contextView: View?, contextPosition: Int, position: Int) {
        (parentFragment as CommentDetailFragment).saveRecord(0, list[position])
        list.removeAt(contextPosition)
        audioListAdapter.notifyItemRemoved(contextPosition)
        audioListAdapter.notifyItemRangeRemoved(contextPosition, list.size)
    }

    override fun showPopupList(adapterView: View?, contextView: View?,
            contextPosition: Int): Boolean {
        return true
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if(hidden){
            audioRecord.stopRecord()
            mediaPlayer?.stop()
        }
    }
}
